package com.sz.web.account.service.serviceImp;

import com.sz.web.account.entity.AccountFunction;
import com.sz.web.account.mapper.AccountFunctionMapper;
import com.sz.web.account.service.AccountFunctionService;
import com.sz.web.common.pojo.ReturnPojo;
import com.sz.web.util.ReturnUtil;
import com.sz.web.util.StringUtils;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

@Service
public class AccountFunctionServiceImp implements AccountFunctionService {

    @Resource
    AccountFunctionMapper accountFunctionMapper;

    @Override
    public ReturnPojo functionQuery() {
        return ReturnUtil.success(accountFunctionMapper.selectAll());
    }

    @Override
    public ReturnPojo functionQueryByRole(Integer id) {

        if (null == id){
            return ReturnUtil.fail("不存在的角色!");
        }
        Map<Object,Boolean> functionMap = new LinkedHashMap<>();

        List<AccountFunction> accountFunctionsByRole = accountFunctionMapper.selectByRoleId(id);
        List<AccountFunction> accountFunctions = accountFunctionMapper.selectAll();

        for (AccountFunction accountFunction:accountFunctionsByRole){
            if (accountFunctions.contains(accountFunction)){
                functionMap.put(accountFunction, true);
            }else {
                functionMap.put(accountFunction, false);
            }
        }
        return ReturnUtil.success(functionMap);
    }

    @Override
    public ReturnPojo functionUpdateNameByUrl(AccountFunction accountFunction) {

        if (null == accountFunction){
            return ReturnUtil.fail("传入数据为空");
        }
        if (StringUtils.isBlank(accountFunction.getControlUrl())){
            return ReturnUtil.fail("未检测到要更新的路由");
        }
        AccountFunction accountFunctionDb = accountFunctionMapper.selectByControlUrl(accountFunction.getControlUrl());
        if (null == accountFunctionDb){
            return ReturnUtil.fail("未查询到改路由的相关信息");
        }

        //模块权限名称
        if (StringUtils.isNotBlank(accountFunction.getFirstMenu())){
            accountFunctionDb.setFirstMenu(accountFunction.getFirstMenu());
        }
        //权限名称
        if (StringUtils.isNotBlank(accountFunction.getFunctionName())){
            accountFunctionDb.setFunctionName(accountFunction.getFunctionName());
        }
        //状态
        if (null != accountFunction.getStatus()){
            accountFunctionDb.setStatus(accountFunction.getStatus());
        }
        //更新时间
        accountFunctionDb.setUpdateTime(new Date());

        int updateCounts = accountFunctionMapper.updateByPrimaryKey(accountFunctionDb);

        if (updateCounts>0){
            return ReturnUtil.success(accountFunctionDb);
        }else {
            return ReturnUtil.fail("未更新数据");
        }
    }
}
